<?php
class UploadController extends BaseController {
	
	protected function _init_() {
		$this->table = $this->db->getTable('attach');
		$postid = $this->input->postid;
		$this->addTab(__('附件上传'), 'upload.upload', array('postid'=>$postid));
		$this->addTab(__('本文附件'), 'upload.post', array('postid'=>$postid));
		$this->addTab(__('附件库'), 'upload.all', array('postid'=>$postid));
	}
	
	public function uploadAction() {
		$postid = $this->input->postid;
		if ($this->input->isPost()) {
			$upload = new Upload();
			$image  = new Image();
			if ( self::config('attach.watermark') ) {
				$image->waterpic   = self::config('attach.waterpic');
				$image->waterpos   = self::config('attach.waterpos');
				$image->watertrans = self::config('attach.watertrans');
			}
			$files = $upload->execute('attach');
			if (empty($files)) {
				$this->assign('errmsg', sprintf('<a href="%s">%s</a>', URL('upload.upload', 'postid='.$postid), __('请选择要上传的文件')));
			} else {
				$idarr = array();
				foreach ($files as $key => $file) {
					if (!$file['err']) {
						$attach = M('Attach');
						$attach->postid = $postid;
						$attach->userid = $this->userid;
						$attach->username = $this->user->username;
						$attach->originalname = $file['name'];
						$attach->filepath = $file['path'];
						$attach->filesize = $file['size'];
						$attach->filetype = $file['type'];
						$attach->fileext  = $file['ext'];
						$attach->dateline = NOW;
						
						$file['isimage'] = stristr($file['type'],'image');
						if ($file['isimage']) {
							//调整图片大小
							if ( self::config('attach.autoresize') ) {
								$image->thumb(DATA_PATH.$file['path'], DATA_PATH.$file['path'], config('resizewidth'), config('resizeheight'), false, config('resizefix'));
							}
							//加水印
							if ( self::config('attach.watermark') ) {
								$image->watermark(DATA_PATH.$file['path']);
							}
							$attach->filesize = filesize(DATA_PATH.$file['path']);
							//读取图标尺寸
							list($width, $height) = getimagesize(DATA_PATH.$file['path']);
							$file['width'] = $width;
							$file['height'] = $height;
						}
						$attach->add();
						if ($attach->error) {
							$file['err'] = 1;
							$file['errmsg'] = $attach->error;
						} else {
							$idarr[] = $file['fileid'] = $attach->id;
							$files[$key] = $file;
						}
					}
				}
				$this->assign('files', $files);
				//临时存放到cookie，发布文章时更新aid
				$idstr = self::cookie('upload_attachments');
				$idstr = preg_match('/^([0-9]+(,[0-9])?)+$/', trim($idstr)) ? trim($idstr) : '';
				!empty($idstr) && $idstr .= ',';
				$idstr .= implode(',', $idarr);
				self::cookie('upload_attachments', $idstr);
			}
		}
		$this->assign('ispost', $this->input->isPost());
		$this->assign('postid', $this->input->postid);
		$this->display();
	}
	
	public function postAction($params = array()) {
		$postid = intval($params['postid']);
		$page = intval($params['page']);
		$pagesize = 10;
		$list = array();
		
		if ($postid > 0) {
			$query = array('postid' => $postid);
			$count = $this->db->count($this->table, "postid = '$postid'");
			if ($count > 0) {
				$sql = "SELECT id,originalname,filepath,filetype,fileext FROM {$this->table}
						WHERE postid = '$postid' ORDER BY id DESC";
				$list = $this->db->getList($sql, $page, $pagesize);
			}
			$pager = new Pager($page, $count, compact('postid'));
			$pagebar = $pager->makeHtml();
			$this->assign(compact('postid', 'list', 'pagebar'));
		}
		
		$this->display();
	}
	
	public function allAction() {
		$page = max(1, intval($this->input->page));
		$year = intval($this->input->year);
		$month = intval($this->input->month);
		$keyword = String::safeStr($this->input->keyword);
		$pagesize = 10;
		
		$mintime = $this->db->getOne("SELECT dateline FROM {$this->table} ORDER BY id ASC LIMIT 1");
		$minyear = self::date($mintime?$mintime:NOW, 'Y');
		$curyear = self::date(NOW, 'Y');
		$list = array();
		
		$url = "?mod=upload&ac=all&postid={$postid}&year={$year}&month={$month}&keyword=".rawurlencode($keyword);
		$wheresql = '1';
		if ($year > 0) {
			if ($month > 0) {
				$month = sprintf('%02d',$month);
				$wheresql .= " AND FROM_UNIXTIME(dateline, '%Y%m') = '{$year}{$month}'";
			} else {
				$wheresql .= " AND FROM_UNIXTIME(dateline, '%Y') = '{$year}'";
			}
		}
		if (!empty($keyword)) {
			$wheresql .= " AND originalname LIKE '%".$this->db->escape($keyword)."%'";
		}
		$count = $this->db->count($this->table, $wheresql);
		if ($count > 0) {
			$sql = "SELECT id,originalname,filepath,filetype,fileext FROM {$this->table} WHERE $wheresql";
			$list = $this->db->getList($sql, $page, $pagesize);
		}
		$pager = new Pager($page, $count, compact('year', 'month', 'keyword'));
		$pagebar = $pager->makeHtml();
		$this->assign(compact('year', 'month', 'keyword', 'minyear', 'curyear', 'list', 'pagebar'));
		$this->display();
	}
	
	public function deleteAction($params = array()) {
		$id = intval($params['id']);
		$attach = M('Attach', $id);
		if ($attach->exists) {
			@unlink(DATA_PATH . $attach->filepath);
			$attach->delete();
			$this->redirect($this->refer);
		}
	}
}